package redisLib

import (
	"context"
	"github.com/go-redis/redis/v8"
	"log"
	"time"
)

const (
	RedisHostPort = "127.0.0.1:6379"
)

const (
	DB0 = iota
	DB1
	DB2
	DB3
	DB4
)
const (
	Session = DB0
	AccessToken = "access_token"
	TokenExpireTime = 7100
	//SessionExpireTime = 108000  // 30d
	SessionExpireTime = 86400 // 1d
	UserID = "userID"
)

func NewRedisClient(db int) *redis.Client {
	return redis.NewClient(&redis.Options{
		Network:            "tcp",
		Addr:               RedisHostPort,
		Username:           "",
		Password:           "",
		DB:                 db,
		MaxRetries:         10,
	})
}

func Set (db int, key string, val interface{}, expSec int) error {
	ctx := context.Background()
	c := NewRedisClient(db)
	defer c.Close()
	err := c.Set(ctx, key, val, time.Duration(expSec * 1000000000)).Err()
	if err != nil {
		log.Printf("set redis err :%s", err)
		return err
	}
	return nil
}

func Get (db int, key string) (string, error) {
	ctx := context.Background()
	c := NewRedisClient(db)
	defer c.Close()
	res, err := c.Get(ctx, key).Result()
	if err != nil {
		log.Printf("get redis error :%s", err)
		return "", nil
	}
	return res, nil
}
func HMSet (db int, key string, field string, val string) error {
	ctx := context.Background()
	c := NewRedisClient(db)
	defer c.Close()
	err := c.HMSet(ctx, key, field, val).Err()
	if err != nil {
		log.Printf("set redis err :%s", err)
		return err
	}
	return nil
}

func HMGet (db int, key string, field string) ([]interface{}, error) {
	ctx := context.Background()
	c := NewRedisClient(db)
	defer c.Close()
	res, err := c.HMGet(ctx, key, field).Result()
	if err != nil {
		log.Printf("hmget val error: %s", err)
		return nil, err
	}
	return res, nil
}
func HSet(db int, key string, field string, val string) error {
	ctx := context.Background()
	c := NewRedisClient(db)
	defer c.Close()
	_, err := c.HSet(ctx, key, field, val).Result()
	if err != nil {
		log.Printf("redis hset val error: %s", err)
		return err
	}
	return nil
}

func HGet(db int, key string, field string) (string, error) {
	ctx := context.Background()
	c := NewRedisClient(db)
	defer c.Close()
	res, err := c.HGet(ctx, key, field).Result()
	if err != nil {
		log.Printf("redis hget val error:%s", err)
		return "", err
	}
	return res, nil
}

func Incr(db int, key string) (int64, error) {
	ctx := context.Background()
	c := NewRedisClient(db)
	defer c.Close()
	res, err := c.Incr(ctx, key).Result()
	if err != nil {
		log.Printf("redis incr key error : %s", err)
	}
	return res, nil
}
